﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using DevExpress.XtraGrid.Columns;
using E4RPDevExpress10;
using StationCommon;

namespace Station.Controls
{
    public partial class WorkSheetList : UserControl
    {
        private Controller _controller;

        #region Properties

        public Controller Controller
        {
            set
            {
                _controller = value;
                _controller.WorkSheetSaved += delegate { SetGridDataSource(); };
                SetGridDataSource();
            }
        }

        #endregion

        public WorkSheetList()
        {
            InitializeComponent();
            FormatGridColumns();
            gridView.DoubleClick += GridViewDoubleClick;
            gridView.OptionsView.ShowFooter = true;
        }
        
        #region Private Methods

        private void SetGridDataSource()
        {
            FolhaObraDataSet dataSet = _controller.WorkSheets();
            gridControl.DataSource = null;
            gridControl.DataSource = dataSet;
            gridControl.DataMember = dataSet.FolhaObra.TableName;
            FormatGridColumns();
        }

        private void FormatGridColumns()
        {
            DevExpressHelper.SetColumnAsCurrency(colValorDesconto);
            DevExpressHelper.SetColumnAsCurrency(colValorSemIva);
            DevExpressHelper.SetColumnAsCurrency(colValorIva);
            DevExpressHelper.SetColumnAsCurrency(colValorComIva);
            var gridColumns = new List<GridColumn>
                                  {
                                      colValorDesconto,
                                      colValorSemIva,
                                      colValorIva,
                                      colValorComIva
                                  };
            DevExpressHelper.ShowGroupSummaryAsCurrency(gridView, gridColumns);
        }

        #endregion

        void GridViewDoubleClick(object sender, EventArgs e)
        {
            if (!_controller.ExistsOpenedWorkSheet(this, "Deseja mesmo abrir folha obra?"))
                return;
            var workSheet = (FolhaObraDataSet.FolhaObraRow)gridView.GetDataRow(gridView.FocusedRowHandle);
            if (workSheet == null)
                return;
            _controller.ShowWorkSheet(workSheet.Id);
        }
    }
}
